package com.cxs.tetrisdemo.tetris;

import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.app.Context;

import static com.cxs.tetrisdemo.common.Constant.GRID_COLS;
import static com.cxs.tetrisdemo.common.Constant.GRID_ROWS;

/*
    画网格 宽10格 * 高20格
    每一格的边长为 height/20
 */
public class TetrisGrid extends Component{

    int len;
    private Paint paint;
    // 当前网格状态
    public char[][] grids = new char[GRID_COLS + 6][GRID_ROWS + 3];
    // 当新的方块即将进入网格时的状态
    public char[][] preGrids = new char[GRID_COLS + 6][GRID_ROWS + 3];
    // 临时网格状态
    public char[][] tmpGrids = new char[GRID_COLS + 6][GRID_ROWS + 3];

    public TetrisGrid(Context context, int len) {
        super(context);
        this.len = len;
        initGrids();
        paint = new Paint();
    }

    /*
        初始化网格状态
        左三列为1，右三列为1， 底部三行为1，其他为0
     */
    private void initGrids() {
        for (int x = 3; x < GRID_COLS + 3; x++) {
            for (int y = 0; y < GRID_ROWS; y++) {
                grids[x][y] = '0';
            }
        }
        // 左三列为1，右三列为1
        for (int x = 0; x < 3; x++) {
            for (int y = 0; y < GRID_ROWS + 3; y++) {
                // 0-2列
                grids[x][y] = '1';
                // 13-15列
                grids[GRID_COLS + 3 + x][y] = '1';
            }
        }
        // 底部三行为1
        for (int x = 0; x < GRID_COLS + 6; x++) {
            for (int y = GRID_ROWS; y < GRID_ROWS + 3; y++) {
                grids[x][y] = '1';
            }
        }
        copyGrids(grids, preGrids);

    }

    public void copyGrids(char[][] source, char[][] target) {
        for (int i = 0; i < source.length; i++) {
            target[i] = source[i].clone();
        }
    }

    // 画 20 * 10 的网格
    public void drawGrid(Canvas canvas) {
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(4);
        // 画20行横线
        for (int i = 0; i < GRID_ROWS; i++) {
            canvas.drawLine(0, len * i, len * GRID_COLS, len *i, paint);
        }
        // 画10列竖线
        for (int i = 0; i < GRID_COLS; i++) {
            canvas.drawLine(len * i, 0, len * i, len * GRID_ROWS, paint);
        }
        // 画4个边框
        paint.setStrokeWidth(20);
        // 上边框
        canvas.drawLine(0, 0, len * GRID_COLS, 0, paint);
        // 下边框
        canvas.drawLine(0, len * GRID_ROWS, len * GRID_COLS, len * GRID_ROWS, paint);
        // 左边框
        canvas.drawLine(0, 0, 0, len * GRID_ROWS, paint);
        // 右边框
        canvas.drawLine(len * GRID_COLS, 0, len * GRID_COLS, len * GRID_ROWS, paint);
    }

    public class Position {
        public int X;
        public int Y;

        public Position(int x, int y) {
            X = x;
            Y = y;
        }
    }
}
